package com.kuaixueit.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kuaixueit.crm.mapper.CStaffMapper;
import com.kuaixueit.crm.mapper.CStaffRoleMapper;
import com.kuaixueit.crm.pojo.CStaff;
import com.kuaixueit.crm.pojo.CStaffRole;
import com.kuaixueit.crm.pojo.QueryVO;
import com.kuaixueit.crm.pojo.ResultVO;
import com.kuaixueit.crm.service.StaffService;

@Service
public class StaffServiceImpl implements StaffService {

	
	@Autowired
	private CStaffMapper staffMapper;
	
	
	@Autowired
	private CStaffRoleMapper staffRoleMapper;
	
	
	@Override
	public void save(CStaff staff) {
		Date date = new Date();
		staff.setCreateTime(date);
		staff.setUpdateTime(date);
		staffMapper.insert(staff);
	}


	@Override
	public PageInfo findPage(QueryVO query,Integer page, Integer rows) {
		//分页插件的使用
		PageHelper.startPage(page, rows);
		//查询
		List list = new ArrayList();
		//查询数据库
		list = staffMapper.findListWithPname(query);
		//查询数据交给分页插件，自动查询总数
		PageInfo info = new PageInfo(list);
		System.out.println("总数："+info.getTotal()+" 当前页数据："+info.getList());
		return info;
	}


	@Override
	public void deleteByIds(Integer[] ids) {
		
		for (int i = 0; i < ids.length; i++){
			//假如ids有10个，删除到第六个出错了
			//2，事务回滚，都没有删除成功
			int deleteByPrimaryKey = staffMapper.deleteByPrimaryKey(ids[i]);
		}
		
	}


	@Override
	public ResultVO update(CStaff staff) {
		Integer id = staff.getId();
		if(null != id){
			staffMapper.updateByPrimaryKey(staff);
			return new ResultVO("修改成功");
		}
		return new ResultVO("修改失败");
	}


	@Override
	public PageInfo findAdmin(Integer page,Integer rows) {
		PageHelper.startPage(page, rows);
		List<Map> list = staffMapper.findAdmin();
		return new PageInfo(list);
	}


	@Override
	public void update(Integer id, Integer[] roids, String username, String password) {
		CStaff staff = new CStaff();
		staff.setId(id);
		//使用md5加密密码
		password= Md5Crypt.md5Crypt(password.getBytes());
		staff.setPassword(password);
		staff.setUsername(username);
		staffMapper.updateByPrimaryKeySelective(staff);
		//删除管理员对应的角色数据
		staffRoleMapper.deleteByStaffID(id);
		//新增数据
		for(Integer roleid:roids) {
			CStaffRole sr = new CStaffRole();
			sr.setRoleId(roleid);
			sr.setStaffId(id);
			staffRoleMapper.insert(sr);
		}
	}


	@Override
	public List findRoleIdsByStaffId(Integer staffId) {
		return staffRoleMapper.selectByStaffID(staffId);
	}

	public static void main(String[] args) {
		System.out.println(Md5Crypt.md5Crypt("dkfadsjfladsjflkadsj".getBytes()));
	}
}
